package ;
import haxe.io.Bytes;
import haxe.Template;
import php.db.Object;
import Auth;
import php.FileSystem;
import php.io.File;
import php.io.FileOutput;
import php.Lib;
import php.NativeArray;
import php.Session;
import php.Web;
/**
 * ...
 * @author Axel Huizinga axel@cunity.me
 */

class Cats extends Object
{
	static var PRIVATE_FIELDS = ["imgUrls, imgMaxWidth"];
	
	public var id:Int;
	public var imgUrls:String;
	public var imgMaxWidth:Int;
	public var name:String;
	public var description:String;
	public var since:Date;
	public var done:Date;
	public var newOwnerId:Int;
	
	public static var manager = new php.db.Manager<Cats>(Cats);
	
	public static function getAll(uType:UserType):List<Cats>
	{		
		return manager.objects(
			(uType == UserType.admin ? "SELECT * FROM Cats":
			"SELECT * FROM Cats WHERE newOwnerId IS NULL ") , uType != UserType.guest
		);
	}
	
	public function displayAllImages(uType:UserType = null):String
	{
		var dbImgs:List<Image> = Image.getAll4(id);
		var t:Template = new Template(File.getContent('site/template/cat.mtt'));
		var res:String = '';
		try
		{
			res = t.execute({ images:dbImgs});
		}
		catch (ex:Dynamic)
		{
			Main.errLog(ex);
		}
		//return t.execute({ admin:uType == UserType.admin, cats:cats});
		return res;		
	}
	
	public static function displayAll(uType:UserType):String
	{
		var catList:List<Cats> = getAll(uType);
		Main.errLog(uType+" catList:" + catList.length);
		var cats:Array<Dynamic> = new Array();
		var cat:Cats;
		if (!(catList == null || catList.isEmpty()))
		{
			for (cat in catList)
			{
				var catObj:Dynamic = cat;
				catObj.image = null;
				//imgMaxWidth = 0;
				var dbImgs:List<Image> = Image.getAll4(cat.id);
				var imgs:List<Image> = new List();
				for (dI in dbImgs)
					imgs.add(dI);
				var r = ~/([\w\-]*\/)+/;
				//cat.imgUrls = '';
				for (img in imgs)
				{
					var url:String = img.url;
					//Main.errLog(url);
					img.url = (r.match(img.url ) ?
					r.replace(img.url, r.matched(0) + Image.thumbsDir):
					Image.thumbsDir + img.url);						
					if (img.isPrimary)
					{
						//cat.imgUrls = cat.imgUrls == '' ?  url : url + ','  + cat.imgUrls;
						catObj.image = img;
					}
					//else
					//cat.imgUrls += cat.imgUrls == '' ?  url : ',' + url;
					//Main.errLog('img.isPrimary:' + Std.string(img.isPrimary));
				}
				//catObj.width = imgMaxWidth;
				if (catObj.image == null && !imgs.isEmpty())
					catObj.image = imgs.first();
				cats.push(catObj);
			}			
		}		
		var t:Template = new Template(File.getContent('site/template/cats.mtt'));
		//Main.errLog("admin:uType =" + uType);
		//Main.errLog("t.execute=" +  t.execute({ admin:uType == UserType.admin, cats:cats}));
		var res:String = '<body><div>' + Std.string(cats.length) + '</div></body>';
		var refresh = Main.param.get('path') == 'dologin' || Main.param.get('task') == 'changeCat';
		Main.errLog('refresh:' + Std.string(refresh));
		try
		{
			res = t.execute( { admin:uType == UserType.admin, cats:cats, refresh:refresh}	);
		}
		catch (ex:Dynamic)
		{
			Main.errLog(ex);
		}
		//return t.execute({ admin:uType == UserType.admin, cats:cats});
		return res;
	}
	
	public function new( param:Hash<String>)
	{
		super();
		try
		{
			name = param.get('name');
			//if (param.exists('description'))
				description = param.get('description');
			insert();
			Main.errLog('inserted:' + Std.string(id));
			var nIm:String = newImages(Util.getFilesInfo());
		}
		catch (ex:Dynamic)
		{
			Main.errLog(ex);
			return;
		}
	}
	
	public static function edit(eid:Int):String
	{
		var c:Cats = manager.get(eid);
		if (c == null)
			return "<body><span>Ungültige Id:" + eid + '</span></body>';
		var imgs:List<Image> = Image.getAll4(eid);
		var r = ~/([\w\-]*\/)+/;
		for (img in imgs)
		{
			img.url = (r.match(img.url ) ?
			r.replace(img.url, r.matched(0) + Image.thumbsDir):
			Image.thumbsDir + img.url);						 
		}
		Main.errLog(c.name);
		var t:HxTemplate = new HxTemplate(File.getContent('site/template/editCats.mtt'));
		//var i:Int = 1;
		//return t.execute( { images:imgs }, { inc:function(res:String->Dynamic, s:String) { return Std.string(i++);}} );
		return t.execute( { cat:c, images:imgs } );
	}
	
	function newImages(out:Hash< Hash < Array<Dynamic> >>):String
	{
		Main.errLog("out.exists('newImage'):" + out.exists('newImage'));
		if (!out.exists('newImage'))
			return '';
		var newFiles:Hash<Array<Dynamic>> = out .get('newImage');
		var k:String = (newFiles != null && newFiles.keys().hasNext() ? newFiles.keys().next() : '');
		var names:Array<Dynamic> = newFiles.get('name');
		var len:Int =  untyped __call__('count', names);
		Main.errLog('len:' + len);
		var param:Hash<String> = Main.param;
		for (fIndex in 0...len)
		{
			if (newFiles.get('error')[fIndex] != 0)
				continue;
			var saved:String = Image.saveFile(newFiles.get('tmp_name')[fIndex], newFiles.get('name')[fIndex]);
			if (saved == null)
			return('<body><div class="error">Fehler beim Speichern von ' + newFiles.get('name')[fIndex] + '</div></body>');
			Image.createThumb(saved);
			var img:Image = new Image();
			img.url = saved;
			img.catId = (id == null? Std.parseInt(param.get('id')) : id);
			img.isPrimary =  (param.exists('isPrimary') && Std.parseInt(param.get('isPrimary')) == fIndex ? true : false);
			Main.errLog(' catId:' + img.catId + ' isPrimary:' + Std.string(img.isPrimary));
			img.insert();
			img.sync();
			if(img.isPrimary)
				Image.setPrimary(img.id, img.catId);			
		}
		return '';
	}
	
	public function change(param:Hash<String>):String
	{
		Main.errLog(~/\r\n|\n/g.replace(param.toString(), '') );
		var output:FileOutput = null;
		var fIndex:Int = 0;
		var param:Hash<String> = Main.param;
		var out:Hash< Hash < Array<Dynamic> >> = Util.getFilesInfo();
		var b:StringBuf = new StringBuf();
		b.add(param.toString());
		b.add(out.toString());
		
		for (key in out.keys())
		{
			if (key.indexOf('image') == 0)
			{
				var imageFile:Hash<Array<Dynamic>> = out.get(key);
				var iid:Int = Std.parseInt(key.substr(key.indexOf('_') + 1));
				Main.errLog('processing:' + key +' iid:' + iid + ' imageOptions_:' + param.get('imageOptions_' + Std.string(iid)) + 
					' status:' + imageFile.get('error')[0] );
				if (imageFile.get('error')[0] == null || imageFile.get('error')[0] == 4)//NO UPLOAD
				{
					if (param.get('imageOptions_' + Std.string(iid)) == 'remove')
					{						
						Image.remove(iid);
						continue;
					}
					if (param.get('imageOptions_' + Std.string(iid)) == 'isPrimary')
					{
						Main.errLog('setPrimary:' +iid );
						Image.setPrimary(iid, Std.parseInt(param.get('id')));
					}
					Main.errLog('status 4 - noUpload:' +iid );
				}
				else if (imageFile.get('error')[0] == 0)//SUCCESSFUL UPLOAD
				{
					var saved:String = Image.saveFile(imageFile.get('tmp_name')[0], imageFile.get('name')[0]);
					if (saved == null)
					return('<body><div class="error">Fehler beim Speichern von ' + imageFile.get('name')[0] + '</div></body>');
					Image.createThumb(saved);					
					var img:Image = new Image();
					img.url = saved;
					img.catId = (id == null? Std.parseInt(param.get('id')) : id);
					img.isPrimary = ( param.exists('isPrimary') && param.get('options_' + Std.string(iid)) == 'isPrimary' ? true : false);
					img.id = iid;
					img.insert();
					Image.setPrimary(img.id, img.catId);						
				}
				
			}
		}
		var nIm = newImages(out);
		if (nIm != '') Main.errLog(nIm);
		var cat:Cats = manager.get(Std.parseInt(param.get('id')), true);
		Main.errLog(param.get('id') + ':' + cat);
		cat.description = param.get('description');
		cat.name = param.get('name');
		cat.update();		
		Main.errLog('done?');
		return displayAll(UserType.admin);
	}
	
}